package com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * @author: mayu
 * @date: 2021年04月09日 11:36
 */
public class TestWithSemaphore {
    //volatile List lists = new ArrayList<>();
    volatile List lists = Collections.synchronizedList(new ArrayList<>());

    void add(Object o) {
        lists.add(o);
    }

    int size() {
        return lists.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {
        TestWithSemaphore tws = new TestWithSemaphore();

        //当前只能有一个线程在执行
        Semaphore s = new Semaphore(1);

        t2 = new Thread(() -> {
            try {
                s.acquire();
                System.out.println("t2结束");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2");

        t1 = new Thread(() -> {
            try {
                s.acquire();
                System.out.println("t1启动");
                for (int i = 0; i < 5; i++) {
                    tws.add(i);
                    System.out.println(i);
                    if (tws.lists.size() == 5) {
                        s.release();
                    }
                }

                t2.start();
                t2.join();

                s.acquire();
                for (int j = 5; j < 10; j++) {
                    tws.add(j);
                    System.out.println(j);
                }
                s.release();
                System.out.println("t1结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1");

        //t2.start();
        t1.start();

    }
}
